package com.tedu.openmedical.statistics.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tedu.openmedical.statistics.mapper.CopyPurposeMapper;
import com.tedu.openmedical.statistics.mapper.RecordCopyStatisticsMapper;
import com.tedu.openmedical.statistics.pojo.dto.*;
import com.tedu.openmedical.statistics.pojo.vo.*;
import com.tedu.openmedical.statistics.service.RecordCopyStatisticsService;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@Service
@Slf4j
public class RecordCopyStatisticsImpl implements RecordCopyStatisticsService {


    @Autowired
    RecordCopyStatisticsMapper recordCopyStatisticsMapper;
    @Autowired
    RangeDate rangeDate;
    public static LocalDate getFirstDayOfWeek(LocalDate date) {
        return date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));     }
    public static LocalDate getLastDayOfWeek(LocalDate date) {
        return getFirstDayOfWeek(date).plusDays(6);
    }
    public static LocalDate getFirstDayOfPreviousWeek(LocalDate date) {
        LocalDate firstDayOfWeek = getFirstDayOfWeek(date);
        return firstDayOfWeek.minusWeeks(1);
    }

    public static LocalDate getLastDayOfPreviousWeek(LocalDate date) {
        LocalDate lastDayOfWeek = getLastDayOfWeek(date);
        return lastDayOfWeek.minusWeeks(1);
    }
    @Override
    public List<Integer> selectCopy(Date todayDate) {
        List<Integer> reNumber=new ArrayList<>();
        //查询今天
       reNumber.add(0,recordCopyStatisticsMapper.selectToday(todayDate));
       //toweek
        // 将Date转换为Instant（Instant是Java 8引入的，表示时间线上的一个点）
        Instant instant = todayDate.toInstant();

        // 使用系统默认时区将Instant转换为LocalDate
        // 注意：LocalDate本身不包含时区信息，但这里我们通过ZoneId.systemDefault()来转换
        LocalDate localTodayDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();

        LocalDate startDate=getFirstDayOfWeek(localTodayDate);
        LocalDate endDate=getLastDayOfWeek(localTodayDate);
        LocalDate lastStartDate=getFirstDayOfPreviousWeek(localTodayDate);
        LocalDate lastEndDate=getLastDayOfPreviousWeek(localTodayDate);

        log.debug("开始时间和结束时间 "+ startDate +endDate );
        int i = recordCopyStatisticsMapper.selectToweek(startDate, endDate);
        reNumber.add(1,i);
        System.out.println(i);

        //toMoon
        reNumber.add(2,recordCopyStatisticsMapper.selectTomoon(todayDate));

        //toYear
        reNumber.add(3,recordCopyStatisticsMapper.selectToyear(todayDate));
        //lastDay
        reNumber.add(4,recordCopyStatisticsMapper.selectLastday());
        //lastWeek
        reNumber.add(5,recordCopyStatisticsMapper.selectLastweek(lastStartDate,lastEndDate));
        //lastMoon
        reNumber.add(6,recordCopyStatisticsMapper.selectLastmoon());
        //lastYear
        reNumber.add(7,recordCopyStatisticsMapper.selectLastyear());
        //total
        reNumber.add(8,recordCopyStatisticsMapper.selectTotal());
        log.debug("查询结果 {}", reNumber);
        log.info("查询结果 {}", reNumber);
        return reNumber;
    }

    @Override
    public  ReportChartsDate selectChartsData(SelectDate selectDate) throws ParseException {
        log.debug("查询起时间 {}", selectDate.getSelectByDate()[0]);
        log.debug("查询至时间 {}", selectDate.getSelectByDate()[1]);
//      传入的是Date 但是目标格式不对 处理日期格式
//        for(int i = 0; i < selectDate.getSelectByDate().length; i++)
//        {
//            selectDate.getSelectByDate()[i]=changeDateType(selectDate.getSelectByDate()[i]);
//        }
        log.debug("修改后的日期格式 起 ："+selectDate.getSelectByDate()[0]+"至："+selectDate.getSelectByDate()[1]);
        //创建目标日期数组

                   String[] rangeDateString=calculateDateRange(selectDate.getSelectByDate()[0],selectDate.getSelectByDate()[1]);
                   log.debug("生成的时间String"+ Arrays.toString(rangeDateString));
                   SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                   Date[] rangeDate=new Date[rangeDateString.length];
                    for(int i = 0 ; i < rangeDateString.length;i++) {
                        rangeDate[i] = dateFormat.parse(rangeDateString[i]);
                        //        插入目标数据
                        recordCopyStatisticsMapper.insertRangeDate(rangeDate[i]);
                        rangeDateString[i] = changeDateType(rangeDate[i]);


                    }
//       执行一次查询
        rangeDate=recordCopyStatisticsMapper.selectRangeDate();

        log.debug("RangeDate数据"+ rangeDate[0]);
        log.debug("RangeDate数据"+ rangeDate[rangeDateString.length-1]);


//        log.debug(String.valueOf(recordCopyStatisticsMapper.insertRangeDate(rangeDate)));
        //      多表联查
        log.debug("传入第一个时间"+selectDate.getSelectByDate()[0]);
        log.debug("传入第二个时间"+selectDate.getSelectByDate()[1]);

        List<ChartsData> chartsDataList = recordCopyStatisticsMapper.selectRangeDateByData
                (rangeDate[0], rangeDate[rangeDateString.length-1]);
        log.debug("返回的日期是"+ chartsDataList.size());

//        删除rangeDate数据
        recordCopyStatisticsMapper.dropRangeDateTable();
//        Integer[] data=new Integer[rangeDateString.length];
//        Date[] date=new Date[rangeDateString.length];
//        for(int i = 0 ; i <rangeDateString.length; i++)
//        {
//            for(int j =0;j<chartsDataList.size()-1;j++)
//           {
//               log.debug("比较的是"+chartsDataList.get(j).getDate().toString()+"和"+rangeDateString[i]);
//               if (chartsDataList.get(j).getDate().toString().equals(rangeDateString[i]))
//               {
//
//                   data[i] = chartsDataList.get(j).getData();
//                    log.debug("匹配data["+i+"]="+chartsDataList.get(j).getData());
//               } else
//               {
//                   data[i] = 0;
//               }
//               date[i]=chartsDataList.get(j).getDate();
//           }
//
//         }
        int dataLength = rangeDateString.length;
        Integer[] data = new Integer[dataLength];
        Date[] date = new Date[dataLength];

        for (int i = 0; i < dataLength; i++) {
            boolean foundMatch = false;
            if(chartsDataList.size()==0){
                data[i]=0;
                date[i]=rangeDate[i];
            }
            else {
            for (int j = 0; j < chartsDataList.size(); j++) {
                log.debug("比较的是" + chartsDataList.get(j).getDate().toString() + "和" + rangeDateString[i]);
                if (chartsDataList.get(j).getDate().toString().equals(rangeDateString[i])) {
                    data[i] = chartsDataList.get(j).getData();
                    log.debug("匹配data[" + i + "]=" + chartsDataList.get(j).getData());
                    date[i] = rangeDate[j];
                    foundMatch = true;
                    break; // 找到匹配后立即退出内层循环
                }
                date[i]=rangeDate[i];

            }
            if (!foundMatch) {
                data[i] = 0; // 如果没有找到匹配项，则设置为0
            }
            }
        }

        log.debug("返回的data是"+ Arrays.toString(data));
        log.debug("返回的date是"+ Arrays.toString(date));

        ReportChartsDate reportChartsDate=new ReportChartsDate();
        reportChartsDate.setData(data);
        reportChartsDate.setDate(date);
        log.debug("返回的日期是"+ Arrays.toString(reportChartsDate.getDate()));
        return reportChartsDate;
    }

    @Override
    public ReportChartsDate selectBarChartsData(SelectDate selectDate) {
        log.debug("查询起时间 {}", selectDate.getSelectByDate()[0]);
        log.debug("查询至时间 {}", selectDate.getSelectByDate()[1]);
        //调用copy模块 获取复印模块对应关系
        log.debug("restemplate创建中");
        RestTemplate restTemplate=  new RestTemplate();
        log.debug("restemplate创建成功");
        String url="http://localhost:8081/v1/duplicate/copy_content/select?id=&name=&status=";
        // 发起请求
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class );
        String result = response.getBody();
        log.debug("result结果是"+result);
        ObjectMapper objectMapper=new ObjectMapper();
        List<CopyContentVO> data=new ArrayList<>();
        try {
            Response<List<CopyContentVO>> response1 = objectMapper.readValue(result, new TypeReference<Response<List<CopyContentVO>>>(){});
            // 获取 Data
          data =response1.getData();
            log.debug("data是"+data);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        //定义x轴数据
        int xLength=0;

        log.debug(String.valueOf(data.size()));

        for(int i =0 ; i < data.size();i++)
        {
            if(data.get(i).getStatus()==1)
                xLength++;
        }
        String[] xAxis=new String[xLength];
        String[] xAxisId=new String[xLength];

        for(int i =0 ,j=0; i < data.size();i++)
        {
            if(data.get(i).getStatus()==1)
            {
                xAxis[j]=data.get(i).getName();
                xAxisId[j]=data.get(i).getId().toString();
                j++;
            }

        }
        // 发起请求

        //查询阶段日期的相关记录数据放入list1
        List<String> list1=recordCopyStatisticsMapper.selectRangeDateByBarData(selectDate.getSelectByDate()[0], selectDate.getSelectByDate()[1]);
        log.debug(list1.toString());
        //然后对每条list处理 每获取到某个字符就数组中的某个值++
        Integer[] reportData=new Integer[xLength];
        for(int i = 0; i < xLength; i++)
        reportData[i]=0;
        for(int i = 0; i < list1.size(); i++)
        {
            String[] split = list1.get(i).split(",");
            log.debug("处理结果为"+ Arrays.toString(split));
            for (String  ID: split
                 ) {
                for(int j =0 ; j <xLength;j++)
                {
                    if(ID.equals(xAxisId[j]))
                        reportData[j]++;
                }

            }
        }

        ReportChartsDate reportChartsDate=new ReportChartsDate();
        reportChartsDate.setData(reportData);
        reportChartsDate.setXAxis(xAxis);
        log.debug("这个是业务层返回的x轴显示数据" + Arrays.toString(reportChartsDate.getXAxis()));
        log.debug("这个是返回的业务层的结果"+ Arrays.toString(reportChartsDate.getData()));
        //处理数据
        //返回数据
        return reportChartsDate;
    }

    @Autowired
    CopyPurposeMapper copyPurposeMapper;
    @Override
    public  PieReport[] selectPieChartsData(SelectDate selectDate) {
        /**
         * 日期传过来是为了获取当前时间段所有的复印 用途
         * 首先 获取对应的模板关系 对应用途Id 和 用途String  可以调用别的模块的APi
         * 然后获取所有的记录 count * group by 用途Id
         * 放到对象中返回  前端调用渲染就行
         *
         */
     List<Relationship> list=  copyPurposeMapper.selectRelationship();
     Integer[] purposeId=new Integer[list.size()];
     String[] purposeName=new String[list.size()];
     Integer[] purposeTotal=new Integer[list.size()];
     for(int i =0 ; i < list.size();i++)
     {
         purposeId[i]=list.get(i).getId();
         purposeName[i]=list.get(i).getInfo();
         purposeTotal[i]=0;
     }
        List<String> list1=recordCopyStatisticsMapper.selectRangeDateByPieData(selectDate.getSelectByDate()[0], selectDate.getSelectByDate()[1]);
        for(int i =0 ; i < list1.size();i++)
        {
            for(int j =0 ;j < purposeId.length;j++)
            {
                if(list1.get(i).equals(purposeId[j].toString()))
                {
                    purposeTotal[j]++;
                }
            }
        }
       PieReport[] pieReportList= new PieReport[purposeId.length];
        for(int i =0 ;i < purposeId.length;i++)
        {//一定要new一个出来 不然就会空指针异常
            pieReportList[i]=new PieReport();
            pieReportList[i].setName(purposeName[i]);
            pieReportList[i].setTotal(purposeTotal[i]);


        }
        log.debug("返回的饼状图数据是"+ Arrays.toString(pieReportList));
        return pieReportList ;
    }

//    public Date changeDateType(Date date) {
//        SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
//        try {
//            String formattedDate = outFormat.format(date);
//            Date returnDate = outFormat.parse(formattedDate);
//            log.debug("转换后的日期是 {}", returnDate);
//            return returnDate;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    public String changeDateType(Date date) {
      String dateString =  date.toString();
        try {
            // 创建DateTimeFormatter
            DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

            // 解析日期字符串
            LocalDateTime dateTime = LocalDateTime.parse(dateString, inputFormatter);

            // 提取日期部分
            LocalDate dateOnly = dateTime.toLocalDate();

            // 创建新的DateTimeFormatter
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            // 格式化日期
            String formattedDate = dateOnly.format(outputFormatter);

            System.out.println("转换后的日期: " + formattedDate);
            return formattedDate;
        } catch (Exception e) {
            System.err.println("日期解析错误: " + e.getMessage());
            return null;
        }

    }
    public static String[] calculateDateRange(Date startDate, Date endDate) {
        List<String> dates = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);

        while (!calendar.getTime().after(endDate)) {
            String dateString = sdf.format(calendar.getTime());
            dates.add(dateString);
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        // Convert the list to an array
        String[] dateArray = dates.toArray(new String[0]);
        return dateArray;
    }
}
